package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.common.enums.ResponseCode;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     * @return
     */
    @Override
    public R<Map> generateCaptcha() {
        //1.生成验证码
        String code = RandomStringUtils.randomNumeric(4);
        //2.生成redis的key
        String rkey = idWorker.nextId()+"";
        //3.将生成的验证码存放到redis中
        redisTemplate.opsForValue().set(rkey,code,600, TimeUnit.SECONDS);
        //4.封装响应结果
        Map<String, String> map = new HashMap<>();
        map.put("code",code);
        map.put("rkey",rkey+"");
        return R.ok(map);
    }

    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //1.判断请求参数是否为空  admin   123456
        if (vo==null || Strings.isNullOrEmpty(vo.getUsername())
                || Strings.isNullOrEmpty(vo.getPassword())
                || Strings.isNullOrEmpty(vo.getRkey())
        ){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //======================
        //校验验证码
        // 判断用户输入的验证码是否为空
        if (vo==null || Strings.isNullOrEmpty(vo.getCode())){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_NOT_EMPTY.getMessage());
        }
        // 从redis中获取生成的验证码
        String rcode = (String) redisTemplate.opsForValue().get(vo.getRkey());
        // 校验验证码
        if (!rcode.equals(vo.getCode())){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_ERROR.getMessage());
        }
        //=======================
        //2.根据用户名查询数据库
        SysUser user = sysUserMapper.findByUserName(vo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //3.登录成功
        //组装登录成功数据
        LoginRespVo respVo = new LoginRespVo();
        //属性名称与类型必须相同，否则copy不到
        BeanUtils.copyProperties(user,respVo);
        return R.ok(respVo);
    }
}
